package com.tensquarespit2.controller;

import com.tensquarespit2.pojo.Spit;
import com.tensquarespit2.service.Spitservice;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/spit")
public class Spitcontroller {
    @Autowired
    private Spitservice spitservice;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成 功", spitservice.findAll());
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成 功", spitservice.findById(id));
    }

    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Spit spit) {
        spitservice.save(spit);
        return new Result(true, StatusCode.OK, "查询成 功");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable String id, @RequestBody Spit spit) {
        spit.set_id(id);
        spitservice.update(spit);
        return new Result(true, StatusCode.OK, "查询成 功");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        spitservice.deleteById(id);
        return new Result(true, StatusCode.OK, "查询成 功");
    }

    @RequestMapping(value = "/search/{id}/{page}/{size}", method = RequestMethod.GET)
    public Result findSearch(@PathVariable String id, @PathVariable int page, @PathVariable int size) {
        Page<Spit> pageList = spitservice.findByParentid(id, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult(pageList.getTotalElements(), pageList.getContent()));
    }

    @RequestMapping(value = "/dianzan/{id}", method = RequestMethod.PUT)
    public Result dianzan(@PathVariable String id) {
        String userid = "111";
        if (redisTemplate.opsForValue().get("userid") != null) {
            return new Result(false, StatusCode.REMOTEERROR, "点赞失败");
        }
        spitservice.dianzan(id);
        redisTemplate.opsForValue().set("userid", 1);
        return new Result(true, StatusCode.OK, "查询成 功");
    }
}
